public class mergeSort {


    public static void mergeS(int[] array){
        mergeF(array,0,array.length-1);
    }
    private static void mergeF(int[] array,int left,int right){
        if(left>=right) {
            return;
        }
        int mid = left + ((right - left)>>1);
        //拆成两半
        mergeF(array,left,mid);
        mergeF(array,mid+1,right);
        //合并
        merge(array,left,mid,right);
    }

    /**
     * 合并，两个有序集作为一个组
     */
    private static void merge(int[] array,int left,int mid,int right) {
        int[] arrTmp = new int[right-left+1];
        int s1 = left;
        int e1 = mid;
        int s2 = mid+1;
        int e2 = right;
        int k = 0;
        while (s1<=e1 && s2<=e2) {
            if(array[s1] > array[s2]) {
                arrTmp[k++] = array[s2++];
            }else {
                arrTmp[k++] = array[s1++];
            }
        }
        while (s1<=e1) {
            arrTmp[k++] = array[s1++];

        }
        while (s2<=e2) {
            arrTmp[k++] = array[s2++];

        }
        for (int i = 0; i < arrTmp.length; i++) {
            array[i+left] = arrTmp[i];
        }
    }
    /**
     *  归并排序非递归写法
     */
    public static void mergeSortNor(int[] array) {
        int gap = 1;//一组的数据个数
        //循环一次，排序两个组
        while (gap < array.length) {
            for (int i = 0; i < array.length; i = i+2*gap) {
                int left = i;
                int mid = left+gap-1;
                //两个if，防止数组越界
                if(mid >= array.length) {
                    mid = array.length-1;
                }
                int right = mid+gap;
                if(right >= array.length) {
                    right = array.length-1;
                }
                merge(array,left,mid,right);
            }
            gap = gap*2;
        }
    }



}
